/**
 * Created with IntelliJ IDEA.
 * User: ajhin
 * Date: 2/18/14
 * Time: 6:40 PM
 * To change this template use File | Settings | File Templates.
 */
package com.societyGames.flashForms
{
import com.societyGames.system.EventObject;

import flash.events.Event;
import flash.text.TextField;
import flash.text.TextFormat;

/**
 * Scales text font to fill the space.
 */
public class AutoScaleTextField extends TextField implements IChangeSize
{
  private var _sizeChangedEventObject:EventObject;
  private var _maximumFontSize:Number = 128;
  private var _desiredWidth:Number;
  private var _desiredHeight:Number;

  public function AutoScaleTextField()
  {
    this._sizeChangedEventObject = new EventObject(this, "SIZE_CHANGED", Event);
  }

  override public function set height(value:Number):void
  {
    super.height = value;
    _desiredHeight = value;
    recalculate();
  }

  override public function set width(value:Number):void
  {
    super.width = value;
    _desiredWidth = value;
    recalculate();
  }

  public function set maximumFontSize(value:Number):void
  {
    if (value != _maximumFontSize)
    {
      _maximumFontSize = value;
      recalculate();
    }
  }

  public function get maximumFontSize():Number
  {
    return _maximumFontSize;
  }

  public function get sizeChangedEventObject():EventObject
  {
    return this._sizeChangedEventObject;
  }

  public override function set text(value:String):void
  {
    super.text = value;
    recalculate();
  }

  public override function set htmlText(value:String):void
  {
    super.htmlText = value;
    recalculate();
  }

  private function recalculate():void
  {
    var textFormat:TextFormat = getTextFormat();

    while ((this.textWidth < this._desiredWidth - 4 && this.textHeight < this._desiredHeight - 4) && textFormat.size < _maximumFontSize)
    {
      textFormat.size = int(textFormat.size) + 1;
      this.setTextFormat(textFormat);
    }

    while ((this.textWidth > this._desiredWidth - 4 || this.textHeight > this._desiredHeight - 4) && textFormat.size >= 0)
    {
      textFormat.size = int(textFormat.size) - 1;
      this.setTextFormat(textFormat);
    }

    this.sizeChangedEventObject.dispatchEvent();
  }
}
}
